<template>
    <view class="post-comment-reply">
        <view class="comment-header">
            <view class="comment-count">评论 {{ commentCount }}</view>
            <view class="sortord">
                <han-icon name="sortord" size="34" />
                <text name="sortord-text">{{ '最新' }}</text>
            </view>
        </view>

        <!-- 无评论提示 -->
        <view v-if="commentList.length === 0" class="no-comment">
            <text>暂无评论，快来发表第一条评论吧~</text>
        </view>

        <view class="comment-List">
            <view
                class="comment-item"
                v-for="(comment, index) in commentList"
                :key="comment.commentId"
            >
                <!-- 评论头部 -->
                <view class="comment-header">
                    <image
                        class="active-image"
                        :src="comment.author.avatarUrl"
                    ></image>

                    <!-- 用户部分 -->
                    <view class="user">
                        <view class="user-info">
                            <view class="user-name">{{
                                comment.author.username
                            }}</view>
                            <han-tag
                                v-if="comment.author.userId == authorId"
                                class="comment-author"
                                text="作者"
                            />
                            <han-icon
                                :name="`lv${comment.author.userLevel}`"
                                size="48"
                            />
                        </view>

                        <!-- 时间地点 -->
                        <view class="time-location">
                            <view class="time">{{
                                formatTime(comment.createTime)
                            }}</view>
                            <view class="location">{{ '广东' }}</view>
                        </view>
                    </view>

                    <!-- 点赞 -->
                    <view class="likes">
                        <han-icon name="likes" />
                        <text class="likes-text">{{ comment.likeCount }}</text>
                    </view>
                </view>

                <!-- 评论内容 -->
                <view class="comment-content">
                    <view class="content-text">{{ comment.content }}</view>
                </view>

                <!-- 评论回复 -->
                <view class="comment-reply" v-if="comment.replyCount > 0">
                    <view
                        class="reply-item"
                        v-for="reply in visibleReplies(comment)"
                        :key="reply.replyId"
                    >
                        <!-- 回复头部 -->
                        <view class="reply-header">
                            <image
                                class="active-image"
                                :src="reply.author.avatarUrl"
                            ></image>

                            <!-- 用户部分 -->
                            <view class="user">
                                <view class="user-info">
                                    <view class="user-name">{{
                                        reply.author.username
                                    }}</view>
                                    <han-tag
                                        v-if="reply.author.userId == authorId"
                                        class="comment-author"
                                        text="作者"
                                    />
                                    <han-icon
                                        :name="`lv${reply.author.userLevel}`"
                                        size="48"
                                    />
                                </view>

                                <!-- 时间地点 -->
                                <view class="time-location">
                                    <view class="time">{{
                                        formatTime(reply.createTime)
                                    }}</view>
                                    <view class="location">{{ '广东' }}</view>
                                </view>
                            </view>

                            <!-- 点赞 -->
                            <view class="likes" @click="handleLike">
                                <han-icon name="likes" />
                                <text class="likes-text">{{
                                    reply.likeCount
                                }}</text>
                            </view>
                        </view>

                        <!-- 回复内容 -->
                        <view class="reply-content">
                            <view class="content-text">
                                <text v-if="reply.repliedUser"
                                    >@{{ reply.repliedUser.username }}
                                </text>
                                {{ reply.content }}
                            </view>
                        </view>
                    </view>

                    <!-- 回复数量提示 -->
                    <view
                        v-if="comment.replyCount > 3 && !comment.showAllReplies"
                        class="more-replies"
                        @click="showMoreReplies(comment, index)"
                    >
                        <view class="text"
                            >展开
                            {{ comment.replyCount - 3 }}
                            条回复
                        </view>
                        <han-icon name="open" size="24" class="icon" />
                    </view>

                    <!-- 加载更多按钮 -->
                    <view
                        v-if="
                            comment.showAllReplies &&
                            comment.replyCount > comment.replies.length
                        "
                        class="load-more"
                        @click="loadMoreReplies(comment, index)"
                    >
                        <view class="text">
                            加载更多回复 ({{
                                comment.replyCount - comment.replies.length
                            }}条剩余)
                        </view>
                        <han-icon name="open" size="24" class="icon" />
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import {
    getPostCommentByPostId,
    getPostCommentReplyByCommentId
} from '@/apis/commentReplyAPI';
import { formatTime } from '@/util/dateUtil';

const commentList = ref([]); // 评论列表
const commentCount = ref(0); // 评论总数
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示数量

// 接收父组件传递的数据
const props = defineProps({
    postId: {
        type: [String, Number],
        required: true
    },
    authorId: {
        type: [String, Number],
        required: true
    }
});

// 获取作者 id
const authorId = computed(() => {
    return props.authorId;
});

// 点赞
const handleLike = () => {
    console.log(222);
};

// 获取评论列表
const getCommentList = async () => {
    try {
        // 获取评论列表
        const res = await getPostCommentByPostId(props.postId, {
            page: currentPage.value,
            size: pageSize.value
        });

        if (res.data.code === 20000) {
            const comments = res.data.data.records.map((comment) => ({
                ...comment,
                replies: [], // 初始化回复数组
                loadedReplies: false, // 标记是否已加载回复
                showAllReplies: false, // 是否显示所有回复
                currentReplyPage: 1 // 当前回复页码
            }));

            commentList.value = comments;
            commentCount.value = res.data.data.total;

            // 预加载前3条回复
            for (const comment of comments) {
                if (comment.replyCount > 0) {
                    await loadReplies(comment, 1, 3);
                }
            }
        }
    } catch (error) {
        console.error('获取评论失败:', error);

        uni.showToast({
            title: '获取评论失败',
            icon: 'none'
        });
    }
};

// 加载评论回复
const loadReplies = async (comment, page, size) => {
    try {
        const res = await getPostCommentReplyByCommentId(comment.commentId, {
            page: page,
            size: size
        });

        if (res.data.code === 20000) {
            const replies = res.data.data.records;
            const index = commentList.value.findIndex(
                (c) => c.commentId === comment.commentId
            );

            if (index !== -1) {
                // 如果是第一页，替换现有回复
                if (page === 1) {
                    commentList.value[index].replies = replies;
                }
                // 否则追加回复
                else {
                    commentList.value[index].replies = [
                        ...commentList.value[index].replies,
                        ...replies
                    ];
                }

                commentList.value[index].loadedReplies = true;

                // 更新总回复数
                commentList.value[index].currentReplyPage = page;
            }
        }
    } catch (e) {
        console.error('获取评论回复失败:', e);

        uni.showToast({
            title: '获取评论回复失败',
            icon: 'none'
        });
    }
};

// 显示更多回复
const showMoreReplies = async (comment, index) => {
    // 标记为显示所有回复
    commentList.value[index].showAllReplies = true;

    commentList.value[index].currentReplyPage = 1;

    // 加载第一页10条回复
    await loadReplies(comment, 1, 10);
};

// 加载更多回复
const loadMoreReplies = async (comment, index) => {
    // 计算下一页
    const nextPage = comment.currentReplyPage + 1;

    // 加载下一页回复（每次10条）
    await loadReplies(comment, nextPage, 10);
};

// 获取可见的回复列表
const visibleReplies = (comment) => {
    // 如果标记为显示所有回复，返回所有已加载的回复，否则只显示前3条
    return comment.showAllReplies
        ? comment.replies
        : comment.replies.slice(0, 3);
};

// 使用 watch 监听 postId 变化
watch(
    () => props.postId,
    async (newPostId) => {
        if (newPostId) {
            currentPage.value = 1;
            commentList.value = [];
            commentCount.value = 0;
            await getCommentList(newPostId);
        }
    },
    { immediate: true }
);
</script>

<style lang="scss">
.post-comment-reply {
    padding: 0 20rpx !important;

    .comment-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 20rpx 0;

        .comment-count {
            font-size: $han-font-size-base;
            font-weight: 600;
        }

        .sortord {
            display: flex;
            align-items: center;
            font-size: $han-font-size-md;
            color: $han-global-secondary-font-color;
        }
    }

    .no-comment {
        text-align: center;
    }

    .comment-List {
        padding-bottom: 100rpx;

        .comment-item {
            width: 100%;

            .comment-header {
                display: flex;
                .active-image {
                    width: 80rpx;
                    height: 80rpx;
                    border-radius: 50%;
                    border: 1rpx solid $han-global-border-color;
                }

                .user {
                    display: flex;
                    flex-direction: column;
                    margin-left: 20rpx;

                    .user-info {
                        display: flex;
                        align-items: center;

                        .user-name {
                            font-size: $han-font-size-md;
                            font-weight: 600;
                            margin-right: 10rpx;
                        }

                        .comment-author {
                            margin-right: 10rpx;
                            width: 68rpx;
                            height: 38rpx;
                        }
                    }

                    .time-location {
                        display: flex;
                        align-items: center;
                        font-size: $han-font-size-sm;
                        color: $han-global-secondary-font-color;

                        .time {
                            margin-right: 10rpx;
                        }
                    }
                }

                .likes {
                    margin-left: auto;

                    .likes-text {
                        margin-left: 10rpx;
                    }
                }
            }

            .comment-content {
                padding-left: 100rpx;

                .content-text {
                    font-size: $han-font-size-md;
                    margin-top: 10rpx;
                }
            }

            .comment-reply {
                padding-left: 100rpx;
                margin-top: 10rpx;

                .reply-item {
                    .reply-header {
                        display: flex;
                        align-items: center;

                        .active-image {
                            width: 62rpx;
                            height: 62rpx;
                            border-radius: 50%;
                            border: 1rpx solid $han-global-border-color;
                        }

                        .user {
                            display: flex;
                            flex-direction: column;
                            margin-left: 20rpx;

                            .user-info {
                                display: flex;
                                align-items: center;

                                .user-name {
                                    font-size: $han-font-size-sm;
                                    font-weight: 600;
                                    margin-right: 10rpx;
                                }

                                .comment-author {
                                    margin-right: 10rpx;
                                    width: 68rpx;
                                    height: 38rpx;
                                }
                            }

                            .time-location {
                                display: flex;
                                align-items: center;
                                font-size: $han-font-size-sm;
                                color: $han-global-secondary-font-color;

                                .time {
                                    margin-right: 10rpx;
                                }
                            }
                        }
                        .likes {
                            margin-left: auto;

                            .likes-text {
                                margin-left: 10rpx;
                            }
                        }
                    }

                    .reply-content {
                        padding-left: 82rpx;

                        .content-text {
                            font-size: $han-font-size-md;
                            margin-top: 10rpx;
                        }
                    }
                }
                .more-replies,
                .load-more {
                    display: flex;
                    align-items: center;
                    color: $han-global-secondary-font-color;
                    padding: 10rpx 0;

                    .text {
                        font-size: $han-font-size-sm;
                        margin: 0 10rpx;
                    }

                    .icon {
                        margin-right: 10rpx;
                    }
                }
            }
        }
    }
}
</style>
